package de.openkanban.client.ui.presenter;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.smartgwt.client.util.JSON;

import de.openkanban.client.ui.board.ActivityView;
import de.openkanban.client.ui.board.WhiteBoardView;
import de.openkanban.client.util.RootPanel;
import de.openkanban.shared.dto.ActivityDto;

public class GetActivitiesByBoardIdRequestCallback implements RequestCallback {

	private WhiteBoardView whiteBoardView;

	public GetActivitiesByBoardIdRequestCallback(WhiteBoardView whiteBoardView) {
		this.whiteBoardView = whiteBoardView;
	}

	@Override
	public void onResponseReceived(Request request, Response response) {
		JSONArray jsa = new JSONArray(JSON.decode(response.getText()));

		RootPanel.main.getBoard().getWhiteBoardView().removeActivitiesHLayoutMembers();

		ActivityDto activityDto;
		if (jsa.size() > 0) {
			RootPanel.main.getBoard().showNewKanbanButton();
			for (int i = 0; i < jsa.size(); i++) {
				activityDto = new ActivityDto(jsa.get(i).isObject().toString());

				ActivityView newActivityView = new ActivityView(activityDto, whiteBoardView.getBoardDto().getBoardId());
				whiteBoardView.addActivity(newActivityView);
			}
		} else {
			RootPanel.main.getBoard().hideNewKanbanButton();
		}
	}

	@Override
	public void onError(Request request, Throwable exception) {

	}

}
